let db = require('../db/dbmanager');
const UUID = require('uuid');
const config = require("../db/config");
const log4js        = require('../utils/logUtils');
const logger        = log4js.getLogger('model');
/**
 * 报警信息表
 */
let Timing={
    insert:function(deviceid, channelid, thumb, picture, add_time){
        return new Promise(function (resolve) {
            let sql = "INSERT INTO TIMING(id,add_time,deviceid,channelid,thumb,picture) VALUES ($id, $add_time,$deviceid, $channelid, $thumb, $picture)";
            let key = UUID.v1().replace(/-/g, '');

            let param = {
                $id: key,
                $add_time: add_time,
                $deviceid: deviceid,
                $channelid: channelid,
                $thumb: thumb,
                $picture: picture
            };
            db.sqliteDB.run(sql, param);
            resolve(key);
        });
    },
    // 某时间段是否已经有了报警
    exists:function(deviceid, channelid, add_time){
        let sql = "SELECT * FROM TIMING WHERE deviceid=$deviceid AND channelid=$channelid AND add_time>$add_time";
        let param = {$deviceid:deviceid, $channelid:channelid, $add_time:add_time-config.alertInterval * 1000};
        return new Promise(function (resolve, reject) {
            db.sqliteDB.all(sql, param, function (err, row) {
                if (err) {
                    reject(err);
                } else {
                    resolve(row);
                }
            });
        });

    },
    // 插入前检查
    insertCheck:async function(deviceid,channelid, thumb, picture, add_time){
        let exist = await Timing.exists(deviceid, channelid, add_time);
        if(exist && exist.length>0){
            logger.warn('短时间重复触发，不写入数据库');
            // 已经存在
            return new Promise(function (resolve, reject) {
                reject(false);
            });
        }else{
            return Timing.insert(deviceid,channelid,thumb,picture,add_time);
        }
    },
        /**
         * 查询列表
         * @param {*} page 第几页
         * @param {*} size 每页大小
         * @param deviceid
         * @param channelid
         */
    list: function(page, size, deviceid, channelid){
            return new Promise(function (resolve) {
            let sql = "SELECT * FROM TIMING ";
            let data;
            if (deviceid) {
                sql += " WHERE deviceid = ? AND channelid = ?";
                data = [deviceid, channelid];
            } else {
                data = [];
            }
            sql += ` order by add_time DESC limit ${size} offset ${size}*${page}`;
            db.sqliteDB.all(sql, data, function (err, rows) {
                resolve(rows);
            });
        });
    },
    count: function(deviceid, channelid){
        return new Promise(function (resolve) {
            let sql = "SELECT COUNT(*) as c FROM TIMING ";
            let data;
            if (deviceid) {
                sql += " WHERE deviceid = ? AND channelid = ?";
                data = [deviceid, channelid];
            } else {
                data = [];
            }
            db.sqliteDB.all(sql, data, (err, ret) => {
                resolve(ret[0].c)
            });
        });
    }
};

module.exports = Timing;
